<?php

class Update_User_Data_API_Endpoint {

    public function __construct() {
        add_filter('query_vars', array($this, 'add_query_vars'), 0);
        add_action('parse_request', array($this, 'sniff_requests'), 0);
        add_action('init', array($this, 'add_endpoint'), 0);
    }

    /** Add public query vars
     * 	@param array $vars List of current public query vars
     * 	@return array $vars 
     */
    public function add_query_vars($vars) {
        $vars[] = '__api';
        $vars[] = 'action';
        return $vars;
    }

    /** Add API Endpoint
     * 	This is where the magic happens - brush up on your regex skillz
     * 	@return void
     */
    public function add_endpoint() {
        add_rewrite_rule('^api/update_user_data/?', 'index.php?__api=1&action=fe_update_user_data', 'top');
    }

    /** 	Sniff Requests
     * 	This is where we hijack all API requests
     * 	If $_GET['__api'] is set, we kill WP and serve up pug bomb awesomeness
     * 	@return die if API request
     */
    public function sniff_requests() {
        global $wp;

        if (isset($wp->query_vars['action']) && $wp->query_vars['action'] == "fe_update_user_data") {
            $this->handle_request();
            exit;
        }
    }

    /** Handle Requests
     * 	This is where we send off for an intense pug bomb package
     * 	@return void 
     */
    protected function handle_request() {
        
        global $wp, $wpdb;
        
        $user = wp_get_current_user();
        $user_id = $user->ID;
        
        if (!is_user_logged_in()) {
            $this->send_response('Error', 'El usuario actual no puede modificar datos');
        }
        
        $functions = array('updateSector', 'updateProduct', 'updateColaborators', 'updateEmail', 'updatePassword', 'updateInventory', 'updateConsumption');
        
        if (isset($_POST) && in_array($_POST['func'], $functions)) {

            if ($_POST['func'] == 'updateSector') { //updateSector
            
                $year = $_POST['year'];
                $month = $_POST['month'];
		$sector = $_POST['sector'];
                $subsector = $_POST['subsector'];
                
                $current_year = date('Y');
                $current_month = date('n');

                $wpdb->query($wpdb->prepare("delete from bpa_registry_sector where user_id = %d and (year > %d or (year = %d and month >= %d))", $user_id, $year, $year, $month));

                for ($y = $year; $y <= $current_year; $y++) {
                    $begin_month = $y == $year ? $month : 1;
                    $end_month = $y < $current_year ? 12 : $current_month;
                    for ($m = $begin_month; $m <= $end_month; $m++) {
                        $wpdb->query($wpdb->prepare("insert into bpa_registry_sector (user_id, sector_id, subsector_id, year, month) values (%d, %d, %d, %d, %d)", $user_id, $sector, $subsector, $y, $m));
                    }
                }

                $this->send_response('Ok');
                exit;
                
            } elseif ($_POST['func'] == 'updateProduct') { //updateSector
            
                $year = $_POST['year'];
                $month = $_POST['month'];
		$product = $_POST['value'];
                
                $wpdb->query($wpdb->prepare(
                            "update bpa_registry_product 
                            set product = %s 
                            where user_id = %d 
                            and year = %d 
                            and month = %d", $product, $user_id, $year, $month));

                $this->send_response('Ok');
                exit;
                
            } elseif ($_POST['func'] == 'updateColaborators') { //updateColaborators
                
                $year = $_POST['year'];
                $month = $_POST['month'];
		$value = $_POST['value'];
                
                if (ctype_digit($value)) {

                    $wpdb->query($wpdb->prepare(
                            "update bpa_registry_workers 
                            set number = %d 
                            where user_id = %d 
                            and year = %d 
                            and month = %d", $value, $user_id, $year, $month));
                    
                    $this->send_response('Ok');
                    exit;
                } else {
                    $this->send_response('Error', 'Número inválido');
                    exit;
                }
                
            } elseif ($_POST['func'] == 'updateEmail') { //updateEmail
                
                $oldEmail = $_POST['oldEmail'];
                $newEmail = $_POST['newEmail'];
                $confirmNewEmail = $_POST['confirmNewEmail'];
                if ($user->user_email != $oldEmail) {
                    $this->send_response('Error', 'Correo antiguo incorrecto');
                    exit;
                }
                if ($oldEmail == $newEmail) {
                    $this->send_response('Error', 'El nuevo correo es el mismo que el antiguo');
                    exit;
                }
                if ($newEmail != $confirmNewEmail || $confirmNewEmail == '' || !filter_var($confirmNewEmail, FILTER_VALIDATE_EMAIL)) {
                    $this->send_response('Error', 'El nuevo correo es inválido');
                    exit;
                }
                if (email_exists($newEmail)) {
                    $this->send_response('Error', 'El nuevo correo ya esta siendo usado');
                    exit;
                }
                $user_id = wp_update_user(array('ID' => $user->ID, 'user_email' => trim($newEmail)));
                if (is_wp_error($user_id)) {
                    $this->send_response('Error', 'No se pudo actualizar el correo. Intente nuevamente luego/');
                } else {
                    $this->send_response('Ok', 'El correo fue actualizado correctamente');
                }
                
            } elseif ($_POST['func'] == 'updatePassword') {
                
                $oldPassword = $_POST['oldPassword'];
                $newPassword = $_POST['newPassword'];
                $confirmNewPassword = $_POST['confirmNewPassword'];
                $user = get_user_by('login', $user->user_login);
                if ($user && wp_check_password($oldPassword, $user->data->user_pass, $user->ID)) {
                    
                } else {
                    $this->send_response('Error', 'La contraseña antigua no es correcta');
                    exit;
                }
                if ($newPassword != $confirmNewPassword || $confirmNewPassword == '') {
                    $this->send_response('Error', 'La nuevo contraseña es inválida');
                    exit;
                }
                if ($oldPassword == $newPassword) {
                    $this->send_response('Error', 'La nueva contraseña es la mismo que la antigua');
                    exit;
                }

                $user_id = wp_set_password($newPassword, $user->ID);

                $this->send_response('Ok', 'La contraseña fue actualizada correctamente');
                
            } elseif ($_POST['func'] == 'updateInventory') {
                
                $inventory = $_POST["inventory"];
                $custom_inventory = $_POST["custom_inventory"];
                
                if (is_array($inventory)) {

                    foreach ($inventory as $key => $value) {
                        $wpdb->query($wpdb->prepare("update bpa_inventory_user set quantity = %d where user_id = %d and item_id = %d", $value, $user_id, $key));
                    }
                                       
                    if (is_array($custom_inventory)) {
                        
                        foreach ($custom_inventory as $custom_item) {
                            
                            $wpdb->insert( 
                                'bpa_inventory_item', 
                                array( 
                                    'name' => $custom_item['name'], 
                                    'custom' => 1,
                                    'type_id' => $custom_item['type']
                                ), 
                                array( 
                                    '%s', 
                                    '%d',
                                    '%d'
                                ) 
                            );
                            
                            $new_item_id = $wpdb->insert_id;
                            
                            $wpdb->query($wpdb->prepare(
                                    "insert into bpa_inventory_user(user_id, item_id, quantity)
                                        values(%d,%d,%d)", $user_id, $new_item_id, $custom_item['value']));

                        }
                        
                    }
                    
                    $this->send_response('Ok', 'El inventario fue actualizado correctamente');
                    //$this->send_response('Ok', $msg);
                    
                } else {
                    $this->send_response('Error', 'No se pudo guardar el inventario');
                }
                
            } elseif ($_POST['func'] == 'updateConsumption') {
                
                $type = $_POST["tipo"];
                $subtype = $_POST['subtipo'];

                $year = $_POST['year'];
                $month = $_POST['mes'];
                $quantity = $_POST['cantidad'];
                $price = $_POST['precio'];
 
                $total_meses = count( $month );
                
                for ( $i = 0; $i < $total_meses; $i++ ) {
                    $wpdb->query('UPDATE 
                            `bpa_registry_consumption` 
                        SET 
                            `quantity` = '. $quantity[$i] .', 
                            `price` = '. $price[$i] .'
                        WHERE 
                            `user_id` = '. $user_id .' AND 
                            `type_id` = '. $type .' AND 
                            `subtype_id` = '. $subtype[$i] .' AND 
                            `year` = '. $year .' AND 
                            `month` = '. $month[$i]);
                }
                
                $message = "Su consumo ";
                
                switch($type){
                    case 1: $message .= "de agua ";
                        break;
                    case 2: $message .= "de electricidad ";
                        break;
                    case 3: $message .= "de combustible ";
                        break;
                }
                
                $message .= "ha sido guardado exitosamente";
                
                $this->send_response('Ok', $message);

            } else {
                $this->send_response('Error', 'Llamada inválida');
            }
        } else {
            $this->send_response('Error', 'Llamada inválida');
        }
    }

    /** Response Handler
     * 	This sends a JSON response to the browser
     */
    protected function send_response($status, $msg = '') {
        $response['status'] = $status;
        if ($msg) {
            $response['message'] = $msg;
        }
        header('content-type: application/json; charset=utf-8');
        echo json_encode($response) . "\n";
        exit;
    }

}

new Update_User_Data_API_Endpoint();